package com.cms.admin.action.healthrecord;

import com.alibaba.fastjson.JSONArray;
import com.cms.admin.action.BaseAction;
import com.cms.admin.model.*;
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.healthrecord.GoodsDataStuffRemarkService;
import com.cms.admin.service.healthrecord.GoodsDataUserRemarkService;
import com.cms.admin.service.healthrecord.GoodsDataUserService;
import com.cms.admin.util.Constants;
import com.cms.admin.util.ExcelRead;
import com.cms.admin.util.PropertiesService;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.StringUtil;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class GoodsDataUserAction extends BaseAction implements ModelDriven<GoodsDataUserExt> {

    private TemplateService templateService;
    private GoodsDataUserService goodsDataUserService;
    private GoodsDataStuffRemarkService goodsDataStuffRemarkService;
    private GoodsDataUserRemarkService goodsDataUserRemarkService;
    private GoodsDataUserExt search = new GoodsDataUserExt();
    private PageBean page;
    private GoodsDataUser goodsDataUser;

    public String getHealthRecordsForUpload() {
        return SUCCESS;
    }

    public String getHealthRecordsForConfirm() {
        return SUCCESS;
    }

    public String getHealthRecordsForWait() {
        return SUCCESS;
    }

    public String getHealthRecordsInRelay() {
        return SUCCESS;
    }

    public String getHealthRecordsHasRelay() {
        return SUCCESS;
    }

    public String getHealthRecordsHaspPublish() {
        return SUCCESS;
    }


    public String ajaxQueryHealthRecordList() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        page = new PageBean(search.getCurrentPage(), search.getPageSize());

        List<GoodsDataUser> goodsDataUserList = goodsDataUserService.queryGoodsDataUserList(page, search);
        String res = null;
        try {
            res = getQueryResult(goodsDataUserList, page);
            JSONObject o = new JSONObject();
            o.put("pageCount", page.getTotalPage());
            o.put("content", res);
            return ajaxJsonSuccessMessage(o);
        } catch (Exception e) {
            LOG.error("ajaxQueryUnGoingOrder", e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }
    }

    private String getQueryResult(List<GoodsDataUser> goodsDataUserList, PageBean page)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("goodsDataUserList", goodsDataUserList);
        map.put("page", page);
        map.put("basePath", getBasePath());

        String result = "";
        if (search.getOperFlag() == 2) {
            result = templateService.generateContentByFreeMarker(
                    Constants.TEMPLATE_HEALTH_RECORDS_FORWAIT_QUERY_RESULT, map);
        } else if (search.getOperFlag() == 3) {
            result = templateService.generateContentByFreeMarker(
                    Constants.TEMPLATE_HEALTH_RECORDS_INRELAY_QUERY_RESULT, map);
        } else if (search.getOperFlag() == 4) {
            result = templateService.generateContentByFreeMarker(
                    Constants.TEMPLATE_HEALTH_RECORDS_HASRELAY_QUERY_RESULT, map);
        } else if (search.getOperFlag() == 5) {
            result = templateService.generateContentByFreeMarker(
                    Constants.TEMPLATE_HEALTH_RECORDS_HASPUBLISH_QUERY_RESULT, map);
        } else {
            result = templateService.generateContentByFreeMarker(
                    Constants.TEMPLATE_HEALTH_RECORDS_FORUPLOAD_QUERY_RESULT, map);
        }

        return result;
    }

    public String ajaxQueryHealthRecordsForUpload() {
        //search.setNowDate(new Date());
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        page = new PageBean(search.getCurrentPage(), search.getPageSize());

        List<GoodsDataUser> goodsDataUserList = goodsDataUserService.queryGoodsDataUserList(page, search);
        String res = null;
        try {
            res = getQueryForUploadResult(goodsDataUserList, page);
            JSONObject o = new JSONObject();
            o.put("pageCount", page.getTotalPage());
            o.put("content", res);
            return ajaxJsonSuccessMessage(o);
        } catch (Exception e) {
            LOG.error("ajaxQueryUnGoingOrder", e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }
    }

    private String getQueryForUploadResult(List<GoodsDataUser> goodsDataUserList, PageBean page)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("goodsDataUserList", goodsDataUserList);
        map.put("page", page);
        map.put("basePath", getBasePath());

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_HEALTH_RECORDS_FORUPLOAD_QUERY_RESULT, map);
        return result;
    }


    public String ajaxQueryHealthRecordsForConfirm() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        page = new PageBean(search.getCurrentPage(), search.getPageSize());

        List<GoodsDataUser> goodsDataUserList = goodsDataUserService.queryGoodsDataUserWithPatientList(page, search);
        String res = null;
        try {
            res = getQueryForConfirmResult(goodsDataUserList, page);
            JSONObject o = new JSONObject();
            o.put("pageCount", page.getTotalPage());
            o.put("content", res);
            return ajaxJsonSuccessMessage(o);
        } catch (Exception e) {
            LOG.error("ajaxQueryUnGoingOrder", e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }
    }

    private String getQueryForConfirmResult(List<GoodsDataUser> goodsDataUserList, PageBean page)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("goodsDataUserList", goodsDataUserList);
        map.put("page", page);
        map.put("basePath", getBasePath());

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_HEALTH_RECORDS_FORCONFIRM_QUERY_RESULT, map);
        return result;
    }

    public String ajaxQueryHealthRecordForPreEdit() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        goodsDataUser = goodsDataUserService.queryGoodsDataUserWithDataByRecId(search.getRecid());
        return SUCCESS;
    }

    public String ajaxQueryHealthRecordForPrePublish() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        goodsDataUser = goodsDataUserService.queryGoodsDataUserWithDataByRecId(search.getRecid());
        return SUCCESS;
    }

    public String ajaxUploadHealthExcelFile() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());

        GoodsDataUser goodsDataUser = goodsDataUserService.queryGoodsDataUserByRecId(search.getRecid());
        if (null != goodsDataUser) {
            if (goodsDataUser.getOperFlag() == 0 || goodsDataUser.getOperFlag() == 1) {
                FileInputStream stream = null;
                try {
                    stream = new FileInputStream(search.getExcel());
                    Workbook wb = WorkbookFactory.create(stream);

                    List<GoodsDataUserRemark> remarks = getGoodsDataUserRemarkFromExcelFile(goodsDataUser, wb);
                    if (null == remarks || remarks.size() == 0) {
                        JSONObject o = new JSONObject();
                        o.put("errorCode", -1);
                        o.put("errorMsg", "健康档案数据为空");
                        return ajaxJson(o);
                    } else {
                        List<GoodsDataStuffRemark> goodsDataStuffRemarks=getGoodsDataStuffDefaultRemark(goodsDataUser);
                        goodsDataUserService.updateGoodsDataUserRemark(search, remarks,goodsDataStuffRemarks);
                        JSONObject o = new JSONObject();
                        o.put("errorCode", 0);
                        o.put("errorMsg", "上传健康档案成功");
                        return ajaxJson(o);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    JSONObject o = new JSONObject();
                    o.put("errorCode", -1);
                    o.put("errorMsg", "健康档案读取错误");
                    return ajaxJson(o);
                } finally {
                    if (null != stream) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        stream = null;
                    }
                }
            } else {
                JSONObject o = new JSONObject();
                o.put("errorCode", -1);
                o.put("errorMsg", "健康档案已上传，不能重复上传");
                return ajaxJson(o);
            }

        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该条记录不存在");
            return ajaxJson(o);
        }
    }

    private List<GoodsDataStuffRemark> getGoodsDataStuffDefaultRemark(GoodsDataUser goodsDataUser) {

        List<GoodsDataStuffRemark> goodsDataStuffRemarks = new ArrayList<GoodsDataStuffRemark>();
        String defaultStuffRemarkString = PropertiesService.getString("default_stuff_remark");
        if (!TextUtils.isEmpty(defaultStuffRemarkString)) {
            String[] defaultStuffRemarkTitles = defaultStuffRemarkString.split(",");
            if (defaultStuffRemarkTitles.length > 0) {
                for (String defaultStuffRemarkTitle : defaultStuffRemarkTitles) {

                    GoodsDataStuffRemark goodsDataStuffRemark=new GoodsDataStuffRemark();
                    goodsDataStuffRemark.setDefaultFlag((short) 1);
                    goodsDataStuffRemark.setSubTitle(defaultStuffRemarkTitle);
                    goodsDataStuffRemark.setUpdateDate(new Date());
                    goodsDataStuffRemark.setUserDataId(goodsDataUser.getRecid());
                    goodsDataStuffRemark.setGoodsDataId(goodsDataUser.getGoodsDataId());
                    goodsDataStuffRemark.setGoodsDataName(goodsDataUser.getItemName());
                    goodsDataStuffRemark.setUpdateUserid(((UserList) request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
                    goodsDataStuffRemarks.add(goodsDataStuffRemark);
                }
            }
        }
        return goodsDataStuffRemarks;
    }


    private List<GoodsDataUserRemark> getGoodsDataUserRemarkFromExcelFile(GoodsDataUser goodsDataUser, Workbook wb) throws Exception {
        List<GoodsDataUserRemark> remarks = null;
        //int sheetsSize = wb.getNumberOfSheets();
        int size = 1;
        Sheet sheet = wb.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (row == null) {
                continue;
            }
            int cellNum = row.getLastCellNum();
            if (cellNum < 4) {
                continue;
            }
            Cell questionCell = row.getCell(0);
            Cell answerCell = row.getCell(2);
            String questionValue = ExcelRead.readCellFirstMethod(questionCell).trim();
            String answerValue = ExcelRead.readCellFirstMethod(answerCell).trim();


            if (TextUtils.isEmpty(questionValue) && TextUtils.isEmpty(answerValue)) {
                continue;
            }
            if (TextUtils.isEmpty(questionValue)) {
                GoodsDataUserRemark remark = remarks.get(remarks.size() - 1);
                remark.setAnswer(remark.getAnswer() + "\r\n" + answerValue + "：" + ExcelRead.readCellFirstMethod(row.getCell(3)).trim());
                remarks.remove(remarks.size() - 1);
                remarks.add(remark);
            } else {
                GoodsDataUserRemark remark = new GoodsDataUserRemark();
                remark.setGoodsDataId(goodsDataUser.getGoodsDataId());
                remark.setGoodsDataName(goodsDataUser.getItemName());
                remark.setUserDataId(goodsDataUser.getRecid());
                remark.setAnswer(answerValue + "：" + ExcelRead.readCellFirstMethod(row.getCell(3)).trim());
                remark.setUpdateDate(new Date());
                remark.setUpdateUserid(((UserList) request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());

                if (null == remarks) {
                    remarks = new ArrayList<GoodsDataUserRemark>();
                }

                remark.setQuestion(questionValue);

                remarks.add(remark);
            }
        }
        return remarks;
    }

    /**
     * 客服确认 发布到订单池
     */
    public String ajaxSendGoodsDataUserToStuff() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        GoodsDataUser goodsDataUser = goodsDataUserService.queryGoodsDataUserByRecId(search.getRecid());
        if (null != goodsDataUser) {
            if (goodsDataUser.getOperFlag() == 1) {
                JSONObject param = new JSONObject();
                param.put("recId", goodsDataUser.getRecid());
                param.put("type", 2);
                param.put("docId", ((UserList) request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
                String responseString = serverPostHead("receiveHealthRecord", param);
                JSONObject jsonObject = JSONObject.fromObject(responseString);
                return ajaxJsonSuccessMessage(jsonObject);

            } else {
                JSONObject o = new JSONObject();
                o.put("errorCode", -1);
                o.put("errorMsg", "该健康档案状态为" + goodsDataUser.getOperFlag() + ",无法发送");
                return ajaxJsonSuccessMessage(o);
            }
        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该健康档案记录不存在");
            return ajaxJsonSuccessMessage(o);
        }
    }

    public String ajaxSendGoodsDataUserToStuffAgain() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        GoodsDataUser goodsDataUser = goodsDataUserService.queryGoodsDataUserByRecId(search.getRecid());
        if (null != goodsDataUser) {
            if (goodsDataUser.getOperFlag() == 2) {

                JSONObject param = new JSONObject();
                param.put("recId", goodsDataUser.getRecid());
                param.put("type", 2);
                param.put("docId", ((UserList) request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
                String responseString = serverPostHead("receiveHealthRecord", param);
                JSONObject jsonObject = JSONObject.fromObject(responseString);
                return ajaxJsonSuccessMessage(jsonObject);
            } else {
                JSONObject o = new JSONObject();
                o.put("errorCode", -1);
                o.put("errorMsg", "该健康档案状态为" + goodsDataUser.getOperFlag() + ",无法发送");
                return ajaxJsonSuccessMessage(o);
            }
        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该健康档案记录不存在");
            return ajaxJsonSuccessMessage(o);
        }
    }

    /**
     * 客服撤销确认 状体2变成1
     */
    public String ajaxRevokeGoodsDataUser() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        GoodsDataUser goodsDataUser = goodsDataUserService.queryGoodsDataUserByRecId(search.getRecid());
        if (null != goodsDataUser) {
            if (goodsDataUser.getOperFlag() == 2) {

                search.setOperFlag((byte) 1);
                goodsDataUserService.updateGoodsDataUser(search);

                JSONObject o = new JSONObject();
                o.put("errorCode", 0);
                o.put("errorMsg", "success");
                return ajaxJsonSuccessMessage(o);
            } else {
                JSONObject o = new JSONObject();
                o.put("errorCode", -1);
                o.put("errorMsg", "该健康档案状态为" + goodsDataUser.getOperFlag() + ",无法取消");
                return ajaxJsonSuccessMessage(o);
            }
        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该健康档案记录不存在");
            return ajaxJsonSuccessMessage(o);
        }
    }


    /**
     * 生成H5档案
     */
    public String ajaxGenerateHealthRecord() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        GoodsDataUser goodsDataUser = goodsDataUserService.queryGoodsDataUserWithDataByRecId(search.getRecid());

        if (null != goodsDataUser) {
            if (goodsDataUser.getOperFlag() != 4) {
                JSONObject o = new JSONObject();
                o.put("errorCode", -1);
                o.put("errorMsg", "该健康档案状态为：" + goodsDataUser.getOperFlag());
                return ajaxJsonSuccessMessage(o);

            } else {

                GoodsDataStuffRemarkExt goodsDataStuffRemarkExt = new GoodsDataStuffRemarkExt();
                goodsDataStuffRemarkExt.setUserDataId(search.getRecid());
                List<GoodsDataStuffRemark> goodsDataStuffRemarks = goodsDataStuffRemarkService.queryGoodsDataStuffRemarkList(goodsDataStuffRemarkExt);


                GoodsDataUserRemarkExt goodsDataUserRemarkExt = new GoodsDataUserRemarkExt();
                goodsDataUserRemarkExt.setUserDataId(search.getRecid());
                List<GoodsDataUserRemark> goodsDataUserRemarks = goodsDataUserRemarkService.queryGoodsDataUserRemarkList(goodsDataUserRemarkExt);

                String res = null;

                try {
                    res = getHealthRecordH5String(goodsDataUser, goodsDataUserRemarks, goodsDataStuffRemarks);

                    String healthRecordUrl = uploadHealthRecordToOSS(res, goodsDataUser);

                    if (StringUtils.isEmpty(healthRecordUrl)) {
                        JSONObject o = new JSONObject();
                        o.put("errorCode", -1);
                        o.put("errorMsg", "上传失败");
                        return ajaxJsonSuccessMessage(o);
                    } else {
                        GoodsDataUser goodsDataUser11 = new GoodsDataUser();
                        goodsDataUser11.setRecid(search.getRecid());
                        goodsDataUser11.setRecordUrl(healthRecordUrl);
                        goodsDataUser11.setUpdateDate(new Date());
                        goodsDataUser11.setUpdateUserid(((UserList) request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
                        goodsDataUserService.updateGoodsDataUser(goodsDataUser11);
                        JSONObject o = new JSONObject();
                        o.put("errorCode", 0);
                        o.put("errorMsg", "success");
                        return ajaxJsonSuccessMessage(o);
                    }


                } catch (Exception e) {
                    LOG.error("ajaxGenerateHealthRecord", e);
                    JSONObject o = new JSONObject();
                    o.put("errorCode", -1);
                    o.put("errorMsg", "生成健康档案失败");
                    return ajaxJsonSuccessMessage(o);
                }
            }
        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该健康档案记录不存在");
            return ajaxJsonSuccessMessage(o);
        }
    }

    private String getHealthRecordH5String(GoodsDataUser goodsDataUser, List<GoodsDataUserRemark> goodsDataUserRemarkList, List<GoodsDataStuffRemark> goodsDataStuffRemarkList) throws Exception {
        HashMap map = new HashMap();
        map.put("goodsDataUser", goodsDataUser);
        map.put("goodsDataStuffRemarkList", goodsDataStuffRemarkList);
        map.put("goodsDataUserRemarkList", goodsDataUserRemarkList);

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_HEALTH_RECORDS_RESULT, map);
        return result;
    }

    private String uploadHealthRecordToOSS(String content, GoodsDataUser goodsDataUser) {
        String healthRecordUrl = "healthrecord/" + goodsDataUser.getOwnerId() + "_" + System.currentTimeMillis() + ".html";
        try {
            uploadByOss(content, healthRecordUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return healthRecordUrl;
    }

    public String ajaxPublishHealthRecord() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:ajaxPublishHealthRecord");

        GoodsDataUser goodsDataUser = goodsDataUserService.queryGoodsDataUserByRecId(search.getRecid());
        if (null != goodsDataUser) {

            if (goodsDataUser.getOperFlag() == 4) {
                if (TextUtils.isEmpty(goodsDataUser.getRecordUrl())) {
                    JSONObject o = new JSONObject();
                    o.put("errorCode", -1);
                    o.put("errorMsg", "发布失败，健康档案H5还没生成");
                    return ajaxJsonSuccessMessage(o);
                } else {
                    JSONObject param = new JSONObject();
                    param.put("recId", goodsDataUser.getRecid());
                    param.put("type", 5);
                    param.put("docId", ((UserList) request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
                    String responseString = serverPostHead("receiveHealthRecord", param);
                    JSONObject jsonObject = JSONObject.fromObject(responseString);
                    return ajaxJsonSuccessMessage(jsonObject);
                }
            } else {
                JSONObject o = new JSONObject();
                o.put("errorCode", -1);
                o.put("errorMsg", "该健康档案状体是:" + goodsDataUser.getOperFlag() + ",发布失败");
                return ajaxJsonSuccessMessage(o);
            }
        } else {
            JSONObject o = new JSONObject();
            o.put("errorCode", -1);
            o.put("errorMsg", "该健康档案记录不存在");
            return ajaxJsonSuccessMessage(o);
        }
    }


    @Override
    public GoodsDataUserExt getModel() {
        return search;
    }

    public TemplateService getTemplateService() {
        return templateService;
    }

    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

    public GoodsDataUserService getGoodsDataUserService() {
        return goodsDataUserService;
    }

    public void setGoodsDataUserService(GoodsDataUserService goodsDataUserService) {
        this.goodsDataUserService = goodsDataUserService;
    }

    public GoodsDataStuffRemarkService getGoodsDataStuffRemarkService() {
        return goodsDataStuffRemarkService;
    }

    public void setGoodsDataStuffRemarkService(GoodsDataStuffRemarkService goodsDataStuffRemarkService) {
        this.goodsDataStuffRemarkService = goodsDataStuffRemarkService;
    }

    public GoodsDataUserRemarkService getGoodsDataUserRemarkService() {
        return goodsDataUserRemarkService;
    }

    public void setGoodsDataUserRemarkService(GoodsDataUserRemarkService goodsDataUserRemarkService) {
        this.goodsDataUserRemarkService = goodsDataUserRemarkService;
    }

    public GoodsDataUser getGoodsDataUser() {
        return goodsDataUser;
    }

    public void setGoodsDataUser(GoodsDataUser goodsDataUser) {
        this.goodsDataUser = goodsDataUser;
    }
}
